package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Brand;
import cn.edu.scau.cmi.ema.domain.Food;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("BrandService")
@Transactional

public class BrandServiceImpl extends CmiEmaService implements BrandService {
	public BrandServiceImpl() {
	}

	@Transactional
	public Brand saveBrand(Brand brand) {
		Set<Food> existingFoodsForBrand = new HashSet<Food>();

		Set<Food> selectedFoodsForBrand = brand.getFoodsForBrand();

		if (brand.getId() == null) {

			Brand existingBrand = brandDAO.findBrandByPhysicalPrimaryKey(brand.getName());

			if (isEquals(brand, existingBrand)) {
				return existingBrand;
			}

			brand = brandDAO.store(brand);
			brandDAO.flush();

			for (Food relatedFood : selectedFoodsForBrand) {
				relatedFood.setBrand(brand);
				foodDAO.store(relatedFood);
			}
		} else {
			Brand existingBrand = brandDAO.findBrandByPrimaryKey(brand.getId());

			existingFoodsForBrand = existingBrand.getFoodsForBrand();

			Set<Food> prepareDeleteFoodsForBrand = new HashSet<Food>();
			Set<Food> prepareAddFoodsForBrand = new HashSet<Food>();

			prepareDeleteFoodsForBrand.addAll(selectedFoodsForBrand);
			prepareDeleteFoodsForBrand.addAll(existingFoodsForBrand);

			prepareAddFoodsForBrand.addAll(selectedFoodsForBrand);
			prepareAddFoodsForBrand.addAll(existingFoodsForBrand);

			prepareDeleteFoodsForBrand.removeAll(selectedFoodsForBrand);
			prepareAddFoodsForBrand.removeAll(existingFoodsForBrand);

			for (Food relatedFood : prepareAddFoodsForBrand) {
				relatedFood.setBrand(brand);
				foodDAO.store(relatedFood);
			}

			for (Food relatedFood : prepareDeleteFoodsForBrand) {
				relatedFood.setBrand(null);
				foodDAO.store(relatedFood);
			}
			brand = brandDAO.store(brand);
			brandDAO.flush();
		}

		foodDAO.flush();
		return brand;
	}

	public void deleteBrand(Brand brand) {
		brandDAO.remove(brand);
		brandDAO.flush();
	}

	@Transactional
	public void deleteBrands(Set<Integer> deleteBrandsId) {
		Query query = brandDAO.createNamedQuery("deleteBrandsById", -1, -1);
		query.setParameter(1, deleteBrandsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Brand> loadBrands() {
		return brandDAO.findAllBrands();

	}

	@Transactional
	public Set<Brand> loadReferenceBrands(Set<Brand> brands) {
		Iterator<Brand> brandsIterator = brands.iterator();
		Set<Brand> referencedBrands = new HashSet<>();
		while (brandsIterator.hasNext()) {
			Brand currentBrand = brandsIterator.next();

			if (!currentBrand.getFoodsForBrand().isEmpty()) {
				referencedBrands.add(currentBrand);
				continue;
			}
		}
		return referencedBrands;
	}

	public Set<Brand> loadBrandsByIdSet(Set<Integer> brandIdSet) {

		Iterator<Integer> brandIdIterator = brandIdSet.iterator();
		Set<Brand> brandSet = new HashSet<>();
		while (brandIdIterator.hasNext()) {
			Integer id = brandIdIterator.next();
			Brand currentBrand = brandDAO.findBrandById(id);
			brandSet.add(currentBrand);
		}
		return brandSet;
	}

	@Transactional
	public List<Brand> findAllBrands(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Brand>(brandDAO.findAllBrands(startResult, maxRows));
	}

	@Transactional
	public Brand findBrandByPrimaryKey(Integer id) {
		return brandDAO.findBrandByPrimaryKey(id);
	}

	@Transactional
	public Integer countBrands() {
		return ((Long) brandDAO.createQuerySingleResult("select count(o) from Brand o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countBrands(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Brand.class);
		return ((Long) brandDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countBrandsByName(String queryName) {
		Query query = brandDAO.createNamedQuery("countBrandsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countBrandsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Brand.class);
//		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return 1;// new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadBrandObjectReferencedSet(Brand brand) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> foodsIds = new HashSet<Integer>();
		for (Food obj : brand.getFoodsForBrand()) {

			foodsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("foodsIds", foodsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadBrandClassReferencedSet(Brand brand) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());

		return classReferencedSetMap;
	}

	public boolean isEquals(Brand brand, Object obj) {
		if (obj == brand)
			return true;
		if (!(obj instanceof Brand))
			return false;
		Brand comparedBrand = (Brand) obj;
		if (!CheckPropertyEqual(brand.getName(), comparedBrand.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

